package com.gjt.thread.Thread;

import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created with Intel IDEA.
 * 计算多个文件的安全散列算法摘要（受I/O的程序） 程序运行的速度比网络提供的速度快
 * 使用线程实现Runnable
 *
 * @Auther: gjt
 * @Date: 2024/3/20 15:52
 */
public class DigestRunnable implements Runnable{

    private String fileName;

    public DigestRunnable(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public void run() {
        try(InputStream in = Files.newInputStream(Paths.get(fileName))){
            MessageDigest sha = MessageDigest.getInstance("SHA-256");
            DigestInputStream din = new DigestInputStream(in, sha);
            while(din.read() != -1);
            byte[] digest = sha.digest();

            StringBuilder result = new StringBuilder(fileName);
            result.append(": ");
            result.append(DatatypeConverter.printHexBinary(digest));
            System.out.println(result);
        }catch (IOException e){
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            System.err.println(e.getMessage());
        }
    }

}
